######################
### Create Map     ###
######################
#   - Apr 20 /Tine ###
######################
#

rm(list = ls())

library('rgdal')
library(readstata13)
library(ggplot2)
library(sf)


#

setwd("/Volumes/GoogleDrive/My Drive/NYU/Projects/Norway/Data")

#

kommuner1921 <- readOGR(dsn = "./kommuner_1921", layer = "kommuner_1921")
data <- read.dta13("prreddata.dta", generate.factors=TRUE)

# keep only useful variables #
myvars <- c("Kommuner", "time", "forcedswitch")
data <- data[myvars]

data <- data[ which(data$time==1919), ]


# merge data #

mapdata <- merge(kommuner1921, data, by.x="KOMMNR", by.y="Kommuner")

mapdata@data$id = rownames(mapdata@data)

mapdatadf <- fortify(mapdata, region = "id")
mapdatadf <- merge(mapdatadf, mapdata@data, by = "id")



# plot map #

mapplot<- ggplot(data = mapdatadf, 
                 aes(x=long,y=lat, group = group, fill = factor(forcedswitch))) +
  geom_polygon()  +
  geom_path(color = "black", size=0.1) +
  theme_bw() +
  theme(panel.border = element_blank(), panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), axis.line = element_blank(), 
        axis.ticks.x=element_blank(), axis.ticks.y=element_blank()) +
  coord_equal() +
  scale_fill_manual(values=c("0"="white", "1"="grey35"), na.value='grey75', labels = c('PR', 'Maj', 'Below Mean')) +
  theme(legend.position = "none", title = element_blank(),
        axis.text = element_blank(), legend.title=element_blank()) 

ggsave("PRmap2022.pdf", plot = mapplot)

